<template>
  <div class="search-credit-info-container">
    <HeaderIndex title="资信智查" />
    <div class="search-inp">
      <form action="/search" >
        <van-search
          v-model.trim="inputValue"
          show-action
          placeholder="请输入公司名"
          @search="handleInpChange"
          background="#e0e0e0"
          enterkeyhint="搜索"
        >
          <template #action>
            <div @click="handleInpChange">搜索</div>
          </template>
        </van-search>
      </form>
    </div>
    <div
      class="search-list"
      ref="searchList"
      v-show="inputValue && list.length"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        :immediate-check="false"
        offset="0"
        finished-text="数据到底啦~~"
        @load="onLoad"
      >
        <div
          class="search-list-item"
          v-for="(item, index) in list"
          :key="index"
          @click="handleEnterpriseInfoQuery(item.name)"
        >
          <div class="search-list-item-one">
            <span>
              <Hightlight
                class="hightlight-title"
                :highlight="{
                  keyword: inputValue,
                  caseSensitive: true,
                  style: hightlightStyle,
                }"
                >{{ item.name }}</Hightlight
              >
              <em class="iconfont icon-youjiantou"
            /></span>
            <span>省份：{{ item.base | isEmptyData }}</span>
          </div>
          <div class="search-list-item-two">
            <span>
              <p>法定代表人</p>
              <p
                class="legal-representative"
                @click.stop="
                  handleBusinessRole(item.name, item.legalPersonName)
                "
              >
                {{ item.legalPersonName }}
              </p>
            </span>
            <span>
              <p>注册资本</p>
              <p>{{ item.regCapital }}</p>
            </span>
            <span>
              <p>成立日期</p>
              <p>{{ item.estiblishTime | estiblishTime }}</p>
            </span>
          </div>
          <div class="search-list-item-three">
            <p>
              <span class="regStatus"
                ><span>经营状况：</span><span>{{ item.regStatus }}</span></span
              >
            </p>
            <p>
              <span class="creditCode"
                ><span>统一社会信用代码：</span
                ><span>{{ item.creditCode }}</span></span
              >
            </p>
          </div>
        </div>
      </van-list>
    </div>
    <div class="search-history" v-show="historyData.length && !inputValue">
      <div class="text-remove">
        <span>搜索历史</span>
        <span @click="handleHistoryRemove">
          <em class="iconfont icon-shanchu" />
        </span>
      </div>
      <ul>
        <li
          v-for="(itemName, index) in historyData"
          :key="index"
          @click="handleHistoryClick(itemName)"
        >
          {{ itemName }}
        </li>
      </ul>
    </div>
    <van-empty
      class="custom-image"
      v-show="(inputValue && !list.length) || !historyData.length"
    >
      <template #image>
        <img src="../../assets/images/custom-empty-image.png" alt="" />
      </template>
    </van-empty>
  </div>
</template>

<script>
import HeaderIndex from "@/components/header";
import Hightlight from "vue-words-highlight";
import { Toast, jumpPage } from "@/utils";
import { getQueryCredit } from "@/api";
import { debounce as _debounce } from "lodash";
import { decrypt } from "@/utils/encryption.js"
export default {
  name: "SearchCreditInfo",
  components: {
    HeaderIndex,
    Hightlight,
  },
  data() {
    return {
      inputValue: "", //输入框数据
      pageNum: 1, //页码
      historyData: [], //历史数据
      list: [], //搜索的数据
      loading: false, //下拉加载状态
      finished: false, //数据是否加载完
      hightlightStyle: {
        //关键字高亮样式
        color: "#ff0402",
        "font-weight": 400,
      },
    };
  },
  //组件路由守卫
  beforeRouteEnter(to, from, next) {
    // 从企业详情返回和商业角色页面到搜索页面需要缓存
    if(from.meta.isEnterSearchCredit){
      next((vm) => {
        vm.inputValue = vm.getLocalStorage()[0];
        vm.handleInpChange();
      });
      return;
    }
    next();
  },
  mounted() {
    //获取本地存储中的历史记录
    this.historyData = this.getLocalStorage();
  },
  methods: {
    /**
     * 获取查询的数据
     * @param {*} pageNum 页码
     * @param {*} isLoadPage 是否加载下一页
     */
    async getData(pageNum = 1, isLoadPage = false) {
      try {
        Toast.startLoading();

        //加载状态开始
        this.loading = true;

        //查找数据
        const { items = [], total } =
          (await getQueryCredit({
            companyName: this.inputValue,
            pageNum,
          })) || {};

        //如果为true，表示加载下一页数据，否则是在搜素内容渲染新的内容
        this.list = isLoadPage ? [...this.list, ...items] : items;

        //数据是否加载完成，显示加载完成文字
        this.finished ||= this.list.length >= total;
      } finally {
        //加载状态结束
        this.loading = false;

        Toast.closeLoading();
      }
    },

    /**
     * 输入框查询 查询时防抖
     */
    handleInpChange: _debounce(function () {
      //有值才做处理
      if (this.inputValue) {
        //将页码重新赋值
        this.pageNum = 1;
        this.list = [];

        //设置列表容器滚动条位置
        $(this.$refs?.searchList).scrollTop(0);

        //获取数据
        this.getData();

        this.handleHistoryUpdate(this.inputValue);
      }
    }, 500),

    /**
     * 历史文本点击事件
     * @param {*} value 文本
     */
    handleHistoryClick(value) {
      //赋值
      this.inputValue = value;

      this.handleHistoryUpdate(this.inputValue);

      //请求数据
      this.getData();
    },

    /**
     * 删除历史文本数据
     */
    handleHistoryRemove() {
      //删除本地存储中的指定数据
      localStorage.removeItem("historyData");

      //删除数据后，更新界面
      this.historyData = this.getLocalStorage();

    },

    /**
     * 更新历史文本数据
     * @param {*} value 文本
     */
    handleHistoryUpdate(value) {
      //获取搜索的历史数据
      const historyArr = this.getLocalStorage();

      //限制历史记录展示 如果数组长度大于等于了20，去除数组最后一项
      historyArr.length >= 20 && historyArr.pop();

      //添加查找文本
      historyArr.unshift(value);

      //数组内容去重 存储到本地存储中
      localStorage.setItem(
        "historyData",
        JSON.stringify([...new Set(historyArr)])
      );

      this.historyData = this.getLocalStorage();
    },

    /**
     * 获取本地存储数据
     */
    getLocalStorage() {
      return JSON.parse(localStorage.getItem("historyData")) ?? [];
    },

    /**
     * 加载下一页，滚动条与底部距离小于 offset 时触发
     */
    onLoad() {
      this.pageNum += 1;

      setTimeout(() => {
        //请求数据
        this.getData(this.pageNum, true);
      }, 300);
    },

    /**
     * 删除输入框内容
     */
    handleRemoveInpVal() {
      $(this.$refs?.searchList).scrollTop(0);
      this.inputValue = "";
      this.list = [];
      this.pageNum = 1;
    },

    /**
     * 进入企业详情信息页面
     * @param {*} companyName 公司名称
     */
    handleEnterpriseInfoQuery(companyName) {
      sessionStorage.setItem("isGoBack", false);
      jumpPage(this, "EnterpriseInfoQuery", {
        companyName,
      });
    },

    /**
     * 进入商业角色页面
     * @param {*} companyName 公司名称
     * @param {*} humanName 人名
     */
    handleBusinessRole(companyName, humanName) {
      jumpPage(this, "BusinessRole", {
        companyName,
        humanName,
      });
    },
  },
  filters: {
    /**
     * 成立日期字段数据截取 年月日格式
     * @param {*} date 日期
     */
    estiblishTime(date) {
      return date?.substr(0, 10) ?? decrypt(process.env.VUE_APP_DEFAULT_SHOW_TEXT);
    },
  },
};
</script>

<style lang="less">
@import url("~@/assets/styles/resetComponentStyle.less");
</style>

<style lang="less" scoped>
@import url("~@/assets/styles/searchCreditInfo/index.less");
</style>